<?php

namespace App\Trip\Wechat\MiniApp;

use App\Models\Common\Channel\Channel;
use App\Models\Common\Channel\Repositories\Interfaces\ChannelRepositoryInterface;
use Exception;

class MiniAppConfig
{
    private $config;

    public function __construct(?array $config)
    {
        $this->setConfig($config);
    }

    public function getConfig(): array
    {
        return $this->config;
    }

    /**
     * @throws Exception
     */
    public function setConfig(?array $config)
    {
        /**
         * @var Channel $channel
         */
        $channelRepo = app(ChannelRepositoryInterface::class);
        $channel     = $channelRepo->findChannelByAppId($config['appid']);
        if (!$channel) {
            throw new Exception('channel not found', 500);
        }
        $config       = [
            /**
             * 账号基本信息，请从微信公众平台/开放平台获取
             */
            'app_id'  => $channel->getAppId(),                   // AppID
            'secret'  => $channel->getSecret(),     // AppSecret
            'token'   => '',                                     // Token
            'aes_key' => '',                                     // EncodingAESKey，兼容与安全模式下请一定要填写！！！

            /**
             * 接口请求相关配置，超时时间等，具体可用参数请参考：
             * https://github.com/symfony/symfony/blob/5.3/src/Symfony/Contracts/HttpClient/HttpClientInterface.php
             */
            'http'    => [
                'timeout' => 5.0,
                // 'base_uri' => 'https://api.weixin.qq.com/', // 如果你在国外想要覆盖默认的 url 的时候才使用，根据不同的模块配置不同的 uri
            ],
        ];
        $this->config = $config;
        return $this;
    }
}